Event.observe(window, 'load', function() {
	document.getElementsByClassName('wg-tdilist').each(function(widget) {
		tdilist_bind(widget)
	});
});

function tdilist_id(widget) {
	return widget.id;
}

function tdilist_bind(widget) {
	add = widget.getElementsByClassName('add-')['0'];
	Event.observe(add, 'click',  tdilist_edit_settings.bindAsEventListener(widget, widget, add.href));

	widget.getElementsByClassName('item-').each(function (item) {
		edit = item.getElementsByClassName('edit-')[0].getElementsByTagName('a')[0];
		tdi_oid = edit.href.toQueryParams().oid;
		Event.observe(edit, 'click',    tdilist_edit_settings.bindAsEventListener(item, widget, edit.href));

		up = item.getElementsByClassName('up-')[0];
		if (up && (url = up.parentNode.href)) {
			Event.observe(up, 'click',    tdilist_move_item.bindAsEventListener(item, widget, url));
		}
		down = item.getElementsByClassName('down-')[0];
		if (down && (url = down.parentNode.href)) {
			Event.observe(down, 'click',    tdilist_move_item.bindAsEventListener(item, widget, url));
		}

		try {
		show = item.getElementsByClassName('show_in_main_menu-')[0].getElementsByTagName('a')[0];
		tdi_oid = show.href.toQueryParams().oid;
		Event.observe(show, 'click',    tdilist_show_in_main_menu.bindAsEventListener(item, widget, show.href));
		} catch (e) {
		}

		try {
		hide = item.getElementsByClassName('hide_in_main_menu-')[0].getElementsByTagName('a')[0];
		tdi_oid = hide.href.toQueryParams().oid;
		Event.observe(hide, 'click',    tdilist_show_in_main_menu.bindAsEventListener(item, widget, hide.href));
		} catch (e) {
		}

		//del = item.getElementsByClassName('delete-')[0].getElementsByTagName('a')[0];
		//tdi_oid = del.href.toQueryParams().oid;
		//Event.observe(del, 'click',    tdilist_delete.bindAsEventListener(item, tdi_oid));
	});
}

function tdilist_renderList(widget, obj)
{
	list = widget.getElementsByClassName('list-')['0'];
	url = widget.getElementsByClassName('do-list')['0'].href;
	//obj.visualEffect('highlight', {duration:1.5});

	var cp = new cpaint();
	//cp.set_transfer_mode('POST');
	cp.call(
	    url,
		'ajax_list',
		function (result) {
			if (result.ajaxResponse['0'].data) {
				list.innerHTML = result.ajaxResponse['0'].data;
				tdilist_bind(widget);
			} else {
				obj.addClassName('error-');
			}
		}
	);
}

function tdilist_move_item(event, widget, url)
{
	Event.stop(event);

	var obj = this;
	//obj.visualEffect('highlight', {duration:1.5});

	var cp = new cpaint();
	//cp.set_transfer_mode('POST');
	cp.call(
		url,
		'ajax_moveTdi',
		function (result) {
			if (result.ajaxResponse['0'].data) {
				tdilist_renderList(widget, obj);
			} else {
				obj.addClassName('error-');
			}
		}
	);
}

function tdilist_show_in_main_menu(event, widget, url)
{
	Event.stop(event);

	var obj = this;

	var cp = new cpaint();
	//cp.set_transfer_mode('POST');
	cp.call(
		url,
		'ajax_show_in_main_menu',
		function (result) {
			if (result.ajaxResponse['0'].data) {
				tdilist_renderList(widget, obj);
			} else {
				obj.addClassName('error-');
			}
		}
	);
}


function tdilist_edit_settings(event, widget, url) {
	Event.stop(event);
	//this.visualEffect('highlight', {duration:1.5});

	obj = this;
	var cp = new cpaint();
	//cp.set_transfer_mode('POST');
	cp.call(
		url,
		'ajax_settings_form',
		function (result) {
			if (result.ajaxResponse['0'].data) {
				var popup = $('popup');

				popup.innerHTML = result.ajaxResponse['0'].data;
				popup.show();
				var form = popup.getElementsByTagName('form')['0'];

				tdi_settings_bind_select_itypes_to_views(obj);

				//window.console.log(form);

				$('tdi_access').hide();
				Event.observe(
					popup.getElementsByClassName('link-')['0'],
					'click',
					function (event) { tdi_tabs(); Event.stop(event); }
				);

				Event.observe(
					popup.getElementsByClassName('cancel-')['0'],
					'click',
					function (event) { popup.toggle(); Event.stop(event); }
				);
				Event.observe(
					form.getElementsByClassName('submit-')['0'],
					'click',
					function (event) {
						Event.stop(event);
						//cp.set_transfer_mode(form.method);
						cp.set_response_type('JSON');
						cp.call(
							form.action,
							'ajax_settings_submit',
							function (result) {
								var errors = result.data;
								if (errors) {
									// assign error messages to fields error holders
									for(var name in errors) {
										if (name != 'toJSONString' /* omit cpain method */) {
											$('_' + name).getElementsByClassName('errormsg-')[0].style.display = "block";
											$('_' + name).getElementsByClassName('errormsg-')[0].innerHTML = errors[name];
										}
									}
								} else {
									obj.removeClassName('selected-');
									tdilist_renderList(widget, obj);
									popup.toggle();
								}
							},
							Form.serializeElements(form.getElements())
						);
					}
				);
			} else {
				obj.addClassName('error-');
			}
		}
	);
}


function tdi_settings_bind_select_itypes_to_views(obj) {
    var itype_view = {
	'doc'    : {showfeed: 1, showforum: 1, showalphabet: 1, showfiles: 0, showgallery: 0, showissues: 0 },
	'image'  : {showfeed: 1, showforum: 1, showalphabet: 1, showfiles: 0, showgallery: 1, showissues: 0 },
	'link'   : {showfeed: 1, showforum: 1, showalphabet: 1, showfiles: 0, showgallery: 0, showissues: 0 },
	'file'   : {showfeed: 1, showforum: 1, showalphabet: 1, showfiles: 1, showgallery: 0, showissues: 0 },
	'issue'  : {showfeed: 0, showforum: 0, showalphabet: 0, showfiles: 0, showgallery: 0, showissues: 1 },
	'review' : {showfeed: 1, showforum: 0, showalphabet: 1, showfiles: 0, showgallery: 0, showissues: 0 }
    };

    var n_itype = $('_itype').getElementsByTagName('select')[0];
    var select  = $( '_view').getElementsByTagName('select')[0];
    var view_options = select.getElementsByTagName('option');
    view_options = $A(view_options);

	function a(name) {
		var asseptable = itype_view[name];
		var res = [];
		var i=0;
		view_options.each(function(option) {
			if (asseptable[option.value]) {
				res[i] = option;
				i++;
			}
		});
		return res;
	}

    var view_asseptable_options = {
	'doc': a('doc'),
	'image': a('image'),
	'link': a('link'),
	'file': a('file'),
	'issue': a('issue'),
	'review': a('review')
    };

    function b(name) {
	var options = select.getElementsByTagName('option');
	var selected_value = select.value;
	var _selected_value = null;

	options = $A(options);
	Element.extend(options).each(function(option) { 
	    Element.extend(option).remove();
	});

	var asseptable = view_asseptable_options[name];
	asseptable = $A(asseptable);
	asseptable.each(function(option) {
	    select.appendChild(option);
	    if (option.value == selected_value) {
		_selected_value = option.value;
	    }
	});
	if (_selected_value == null) select.selectedIndex = 0;
	else select.value = _selected_value;
    }

    Event.observe(n_itype, 'change', function(event) { b($F(n_itype)); });
    b($F(n_itype)); 
}

function on_tdi_tabs(event) {
    tdi_tabs(); 
    Event.stop(event); 
}
function tdi_tabs() {

	link = $('popup').getElementsByClassName('link-')['0'];
	selected = $('popup').getElementsByClassName('selected-')['0'];
	
	Event.stopObserving(link, 'click', on_tdi_tabs);
	Event.observe(selected, 'click', on_tdi_tabs);

	link.className = 'selected-';
	selected.className = 'link-';
	
	$('tdi_settings').toggle();
	$('tdi_access').toggle();

}
